package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * @Date 2025/10/22/周三 15:52
 */
@Service
public class WechatServiceImpl implements WechatService {

    //小程序ID
    @Value("${wechat.appId}")
    private String appId;

    //小程序密钥
    @Value("${wechat.secret}")
    private String appSecret;


    //获取手机号API地址
    private static final String POST_PHONE_API_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    //小程序登录API地址
    private static final String GET_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    //获取访问Token的API地址
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";



    /**
     * 获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map paramMap = new HashMap();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result  = HttpUtil.get(GET_OPEN_ID_URL, paramMap);
        if(StringUtils.isBlank(result)) {
            throw new BaseException("获取accessToken失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("openid");
    }

    /**
     * 获取手机号
     *
     * @param code
     * @return
     */
    @Override
    public String getPhoneNum(String code) {
        String accessToken = getAccessToken();
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("code",code);
        String result = HttpUtil.post(POST_PHONE_API_URL + accessToken, JSON.toJSONString(paramMap));
        if(StringUtils.isBlank(result)) {
            throw new BaseException("获取手机号失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        String phoneInfoJSON = jsonObject.getString("phone_info");
        if(StringUtils.isNotBlank(phoneInfoJSON)) {
            JSONObject phoneObject = JSONObject.parseObject(phoneInfoJSON);
            return phoneObject.getString("phoneNumber");
        }
        return null;
    }

    private String getAccessToken() {
        Map paramMap = new HashMap();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        paramMap.put("grant_type", "client_credential");
        String result  = HttpUtil.get(GET_ACCESS_TOKEN_URL, paramMap);
        return JSONObject.parseObject(result).getString("access_token");
    }
}